<?php
$caption = 'Merchants Nearby';
$this->pageTitle = $caption;
?>
<div id="mapView" class="hidden-phone">
	<div id="mapCanvas"></div>
</div>
<div id="filterView">
	<div class="suggestionGrouping">
		<div id="messageBar">
			<div class="message">
				<span><?php echo $caption; ?></span>
			</div>
			<div id="queryRefinements">
				<span class="intro" id="my-location"></span>
			</div>
		</div>
	</div>
	<div class="newFilterControls">
		<ul class="chips">
			<li class="chip info"><input id="search-txt" type="text" name="q" /></li>
			<li class="chip info"><span id="search-btn"> <i class="icon-search"></i> </span></li>
			<li class="chip locate"><span id="locate-me" title="use my current location"> <i class="icon-location-arrow"></i> </span></li>
		</ul>
		<div class="refinements">
			<span class="intro">Try:</span>
			<a class="refinement link" data-term="Drink">Drink</a>,
			<a class="refinement link" data-term="Restaurants">Restaurants</a>,
			<a class="refinement link" data-term="Shopping">Shopping</a>,
			<a class="refinement link" data-term="Beauty">Beauty</a>,
			<a class="refinement link" data-term="Sports">Sports</a>,
			<a class="refinement link" data-term="Arts">Arts</a>,
			<a class="refinement link" data-term="">All</a>
		</div>
	</div>
</div>
<div id="loadingResults"><img src="<?php echo Yii::app()->baseUrl; ?>/img/ajax-loaders/ajax-loader-4.gif" /></div>
<div id="resultsContainer">
	<div id="resultsView"></div>
</div>
<?php
$langcode = Yii::app()->language;
if ($langcode == 'zh_cn') $langcode = 'en';
?>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&amp;libraries=places&amp;language=<?php echo $langcode; ?>"></script>
<script src="<?php echo Yii::app()->baseUrl; ?>/js/jquery.google.map.js?v=<?php echo Yii::app()->params['version']; ?>" type="text/javascript"></script>
<script type="text/javascript">
var refresh = true;
var markers = [];
var mapCav = null;
var activePin = {id:null};
var g_locate = {};
var g_position = {};
var g_keyword = null;
$(function() {
	mapCav = $('#mapCanvas').isMapCanvas('<?php echo Yii::app()->baseUrl; ?>', 1);
	//load data when map is loaded.
	mapCav.triggerMapIdle(function() {
		if (refresh) {
			request_marker(mapCav.getBounds(), g_position, g_keyword);
		}
	});
	if (refresh) {
		request_marker(null, g_position, g_keyword);
	}
	//load data when bounds are changed.
	mapCav.bind('bounds_changed', function() {
		request_marker(mapCav.getBounds(), g_position, g_keyword);
	});
	$('#locate-me').click(function () {
		if (mapCav) {
			mapCav.findMe(function(lat, lng){
				g_locate.lat = lat;
				g_locate.lng = lng;
				var geocoder = new google.maps.Geocoder();
				var latlng = new google.maps.LatLng(g_locate.lat, g_locate.lng);
				geocoder.geocode({'latLng': latlng}, function(results, status) {
					if (status == google.maps.GeocoderStatus.OK) {
						$('#my-location').fadeIn('fast').html(results[0]['formatted_address']);
					} else {
						$('#my-location').fadeOut('fast');
					};
				});
			});
		} else {
			getLocation();
		}
	});
	
	//.refinement.link
	$('.refinement.link').click(function(){
		g_keyword = $(this).data('term');
		$('#search-txt').val(g_keyword);
		request_marker(mapCav.getBounds(), g_position, g_keyword);
	});
	//search form
	$('#search-btn').click(function(){
		g_keyword = $('#search-txt').val();
		request_marker(mapCav.getBounds(), g_position, g_keyword);
	});
});

function request_marker(bounds, position, q) {
	$.ajax({
		url: location.href, data: {bounds:bounds, position:position, q:q},
		type: 'POST', dataType: 'json',
		beforeSend: function() {
			$('#loadingResults').show();
		},
		error: function() {
			$('#loadingResults').hide();
		},
		success: function(json) {
			refresh = false;
			$('#loadingResults').hide();
			mapCav.removeAllPins();
			//bind map markers
			$.map(json.markers, function(v, i) {
				var pinId = 'mid_' + v.id;
				var style = (v.status == 1) ? (v.offers > 0) ? 'org' : 'blue' : 'gray';
				var pin = mapCav.pinHash[pinId];
				if (!pin) {
					mapCav.pin(pinId, {
						style: style,
						category: v.category,
						latitude: v.lat,
						longitude: v.lng,
						onClick: function() {
							v.style=style;
							mapInfoWindow(pinId, v);
						}
					});
				}
			});
			//bind merchant list
			$('#resultsView').html(json.html);
			
			//bind the click event
			$('#resultsView .card').click(function() {
				var pinId = $(this).data('pin-id');
				var pinIndex = $(this).data('pin-i');
				if (pinIndex >= 0) {
					mapInfoWindow(pinId, json.markers[pinIndex]);
				}
			});
		}
	});
}
function mapInfoWindow(pinId, marker) {
	if (!marker.lat || !marker.lng) {return;}
	//clear last activePinId
	if (activePin.id) {
		$('#'+activePin.id).removeClass('select');
	}
	mapCav.removeAllBubbles();
	mapCav.bubble(pinId, {
		latitude: marker.lat,
		longitude: marker.lng,
		content: marker.body,
		offsetVertical: -4,
		size: 'small'
	});
	//panTo with offset
	mapCav.panTo(marker.lat, marker.lng);
	mapCav.panBy(220, 0);
	//scroll to that pin
	activePin.id = pinId;
	
	$(window).scrollTo('#'+pinId, 500, {queue:true,offset:{top:-215}});
	$('#'+pinId).addClass('select');
}

function getLocation() {
	if (navigator.geolocation) {
		var options = {timeout:4000, maximumAge:300000};
		navigator.geolocation.getCurrentPosition(successLocate, errorLocate, options);
	} else {
		//use the default position
		request_marker(mapCav.getBounds(), g_position, g_keyword);
	}
}
function successLocate(position) {
	//loading the offers based on the current position
	g_position = {lat: position.coords.latitude, lng: position.coords.longitude};
	request_marker(mapCav.getBounds(), g_position, g_keyword);
}
function errorLocate(error) {
	var message = 'undefined error.';
	switch (error.code) {
		case error.PERMISSION_DENIED:
			message = "User denied the request for Geolocation."
		break;
		case error.POSITION_UNAVAILABLE:
			message = "Location information is unavailable."
		break;
		case error.TIMEOUT:
			message = "The request to get user location timed out."
		break;
		case error.UNKNOWN_ERROR:
			message = "An unknown error occurred."
		break;
	}
	_push({msg: message, func: 'getLocation'});
	//use the default position
	request_marker(mapCav.getBounds(), g_position, g_keyword);
}
</script>